document.addEventListener('DOMContentLoaded', function () {
    const registerForm = document.getElementById('registerForm');
    const registerButton = document.getElementById('registerButton');
    const registerContainer = document.getElementById('registerContainer');

    // 配置后端API地址
    const API_BASE_URL = 'api/';
    const REGISTER_ENDPOINT = `/register/${API_BASE_URL}`;
    const CHECK_USERNAME_ENDPOINT = `${API_BASE_URL}/check-username/`;
    const CHECK_EMAIL_ENDPOINT = `${API_BASE_URL}/check-email/`;

    // 验证规则
    const validators = {
        firstName: {
            validate: (value) => {
                if (!value.trim()) return '请输入姓名';
                if (value.trim().length < 1) return '姓名不能为空';
                if (value.trim().length > 20) return '姓名不能超过20个字符';
                return null;
            }
        },
        username: {
            validate: (value) => {
                if (!value.trim()) return '请输入用户名';
                if (value.length < 3) return '用户名至少需要3个字符';
                if (value.length > 20) return '用户名不能超过20个字符';
                if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(value)) return '用户名只能包含字母、数字、下划线和中文';
                return null;
            }
        },
        phone: {
            validate: (value) => {
                if (!value.trim()) return '请输入手机号码';
                const phoneRegex = /^1[3-9]\d{9}$/;
                if (!phoneRegex.test(value)) return '请输入有效的手机号码';
                return null;
            }
        },
        password: {
            validate: (value) => {
                if (!value) return '请输入密码';
                if (value.length < 8) return '密码至少需要8个字符';
                if (value.length > 128) return '密码不能超过128个字符';
                return null;
            }
        },
        confirmPassword: {
            validate: (value, formData) => {
                if (!value) return '请确认密码';
                if (value !== formData.password) return '两次输入的密码不一致';
                return null;
            }
        }
    };

    // 密码强度检查
    function checkPasswordStrength(password) {
        const strengthEl = document.getElementById('passwordStrength');
        const strengthText = document.getElementById('strengthText');

        if (!password) {
            strengthEl.className = 'password-strength';
            strengthText.textContent = '请输入密码';
            return;
        }

        let score = 0;
        let feedback = [];

        // 长度检查
        if (password.length >= 8) score++;
        if (password.length >= 12) score++;

        // 字符类型检查
        if (/[a-z]/.test(password)) score++;
        if (/[A-Z]/.test(password)) score++;
        if (/[0-9]/.test(password)) score++;
        if (/[^a-zA-Z0-9]/.test(password)) score++;

        // 根据得分设置强度
        if (score <= 2) {
            strengthEl.className = 'password-strength strength-weak';
            strengthText.textContent = '弱';
        } else if (score <= 3) {
            strengthEl.className = 'password-strength strength-fair';
            strengthText.textContent = '一般';
        } else if (score <= 4) {
            strengthEl.className = 'password-strength strength-good';
            strengthText.textContent = '良好';
        } else {
            strengthEl.className = 'password-strength strength-strong';
            strengthText.textContent = '强';
        }
    }

    // 验证字段
    function validateField(fieldName, value, formData = {}) {
        const validator = validators[fieldName];
        if (!validator) return null;

        const error = validator.validate(value, formData);
        const input = document.getElementById(fieldName);
        const errorEl = document.getElementById(`${fieldName}Error`);
        const successEl = document.getElementById(`${fieldName}Success`);

        if (error) {
            input.classList.add('error');
            input.classList.remove('success');
            errorEl.textContent = error;
            errorEl.style.display = 'block';
            if (successEl) successEl.style.display = 'none';
            return false;
        } else {
            input.classList.remove('error');
            input.classList.add('success');
            errorEl.style.display = 'none';
            if (successEl) {
                successEl.textContent = '✓ 格式正确';
                successEl.style.display = 'block';
            }
            return true;
        }
    }

    // 检查用户名是否可用
    let usernameCheckTimeout;

    async function checkUsernameAvailability(username) {
        if (usernameCheckTimeout) clearTimeout(usernameCheckTimeout);

        usernameCheckTimeout = setTimeout(async () => {
            try {
                const response = await fetch(CHECK_USERNAME_ENDPOINT, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({username})
                });

                const data = await response.json();
                const successEl = document.getElementById('usernameSuccess');

                if (data.available) {
                    successEl.textContent = '✓ 用户名可用';
                    successEl.style.display = 'block';
                } else {
                    validateField('username', username);
                    const errorEl = document.getElementById('usernameError');
                    errorEl.textContent = '用户名已被占用';
                    errorEl.style.display = 'block';
                }
            } catch (error) {
                console.error('检查用户名失败:', error);
            }
        }, 500);
    }


    // 绑定输入事件
    Object.keys(validators).forEach(fieldName => {
        const input = document.getElementById(fieldName);
        if (input) {
            input.addEventListener('blur', function () {
                const formData = getFormData();
                const isValid = validateField(fieldName, this.value, formData);

                // 特殊处理用户名和邮箱的可用性检查
                if (isValid && fieldName === 'username') {
                    checkUsernameAvailability(this.value);
                }
            });

            input.addEventListener('input', function () {
                // 实时密码强度检查
                if (fieldName === 'password') {
                    checkPasswordStrength(this.value);
                }

                // 实时确认密码检查
                if (fieldName === 'confirmPassword') {
                    const formData = getFormData();
                    validateField(fieldName, this.value, formData);
                }
            });
        }
    });

    // 获取表单数据
    function getFormData() {
        return {
            firstName: document.getElementById('firstName').value,
            username: document.getElementById('username').value,
            phone: document.getElementById('phone').value,
            password: document.getElementById('password').value,
            confirmPassword: document.getElementById('confirmPassword').value,
            agreeTerms: document.getElementById('agreeTerms').checked,
            agreeNewsletter: document.getElementById('agreeNewsletter').checked
        };
    }


    // 验证整个表单
    function validateForm() {
        const formData = getFormData();
        let isValid = true;

        // 验证所有字段
        Object.keys(validators).forEach(fieldName => {
            const fieldValid = validateField(fieldName, formData[fieldName], formData);
            if (!fieldValid) isValid = false;
        });

        // 验证协议勾选
        if (!formData.agreeTerms) {
            showMessage('请同意用户协议和隐私政策', 'error');
            isValid = false;
        }

        return isValid;
    }

    // 设置加载状态
    function setLoadingState(isLoading) {
        if (isLoading) {
            registerContainer.classList.add('loading');
            registerButton.textContent = '创建中...';
            registerButton.disabled = true;
        } else {
            registerContainer.classList.remove('loading');
            registerButton.textContent = '创建账户';
            registerButton.disabled = false;
        }
    }

    // 表单提交处理
    registerForm.addEventListener('submit', async function (e) {
        e.preventDefault();

        if (!validateForm()) {
            return;
        }

        const formData = getFormData();
        setLoadingState(true);

        try {
            const response = await fetch(REGISTER_ENDPOINT, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCsrfToken(),
                },
                body: JSON.stringify({
                    first_name: formData.firstName,
                    last_name: "",
                    username: formData.username,
                    email: formData.email,
                    phone: formData.phone,
                    password: formData.password,
                    agree_newsletter: formData.agreeNewsletter
                }),
                credentials: 'include'
            });

            const data = await response.json();

            if (response.ok && data.success) {
                showMessage('注册成功！', 'success');

                // 延迟跳转到登录页面
                setTimeout(() => {
                    window.location.href = data.redirect_url || '/login/';
                }, 2000);

            } else {
                const errorMsg = data.message || data.error || '注册失败，请重试';
                showMessage(errorMsg, 'error');

                // 处理特定错误
                if (data.errors) {
                    Object.keys(data.errors).forEach(field => {
                        const errorEl = document.getElementById(`${field}Error`);
                        if (errorEl) {
                            errorEl.textContent = data.errors[field][0];
                            errorEl.style.display = 'block';
                            document.getElementById(field).classList.add('error');
                        }
                    });
                }
            }

        } catch (error) {
            console.error('注册请求失败:', error);

            if (error.name === 'TypeError' && error.message.includes('fetch')) {
                showMessage('网络连接失败，请检查网络后重试', 'error');
            } else {
                showMessage('注册服务暂时不可用，请稍后重试', 'error');
            }
        } finally {
            setLoadingState(false);
        }
    });

    // 显示消息提示
    function showMessage(message, type = 'info') {
        const existingMsg = document.querySelector('.message-toast');
        if (existingMsg) {
            existingMsg.remove();
        }

        const messageEl = document.createElement('div');
        messageEl.className = `message-toast ${type}`;
        messageEl.textContent = message;

        Object.assign(messageEl.style, {
            position: 'fixed',
            top: '20px',
            right: '20px',
            padding: '12px 20px',
            borderRadius: '8px',
            color: 'white',
            fontSize: '14px',
            fontWeight: '500',
            zIndex: '10000',
            transform: 'translateX(100%)',
            transition: 'transform 0.3s ease',
            maxWidth: '300px',
            wordBreak: 'break-word'
        });

        if (type === 'success') {
            messageEl.style.background = 'linear-gradient(135deg, #48bb78, #38a169)';
        } else if (type === 'error') {
            messageEl.style.background = 'linear-gradient(135deg, #f56565, #e53e3e)';
        } else {
            messageEl.style.background = 'linear-gradient(135deg, #667eea, #764ba2)';
        }

        document.body.appendChild(messageEl);

        setTimeout(() => {
            messageEl.style.transform = 'translateX(0)';
        }, 100);

        setTimeout(() => {
            messageEl.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.parentNode.removeChild(messageEl);
                }
            }, 300);
        }, 3000);
    }

    // 获取CSRF Token
    function getCsrfToken() {
        const csrfCookie = document.cookie
            .split('; ')
            .find(row => row.startsWith('csrftoken='));
        return csrfCookie ? csrfCookie.split('=')[1] : '';
    }

    // 用户协议和隐私政策链接处理
    document.querySelector('a[href="#"]').addEventListener('click', function (e) {
        e.preventDefault();
        showMessage('用户协议页面开发中', 'info');
    });

    document.querySelectorAll('a[href="#"]')[1].addEventListener('click', function (e) {
        e.preventDefault();
        showMessage('隐私政策页面开发中', 'info');
    });

    // 登录链接处理
    document.querySelector('.login-link a').addEventListener('click', function (e) {
        e.preventDefault();
        window.location.href = '/login/';
    });

    // 输入框焦点效果
    const inputs = document.querySelectorAll('.form-input');
    inputs.forEach(input => {
        input.addEventListener('focus', function () {
            this.parentElement.classList.add('focused');
        });

        input.addEventListener('blur', function () {
            this.parentElement.classList.remove('focused');
        });
    });

    // 回车键处理
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Enter') {
            const focusedElement = document.activeElement;
            if (focusedElement.classList.contains('form-input')) {
                e.preventDefault();
                // 如果是最后一个输入框，提交表单
                if (focusedElement.id === 'confirmPassword') {
                    registerForm.dispatchEvent(new Event('submit'));
                } else {
                    // 否则跳转到下一个输入框
                    const inputs = Array.from(document.querySelectorAll('.form-input'));
                    const currentIndex = inputs.indexOf(focusedElement);
                    if (currentIndex < inputs.length - 1) {
                        inputs[currentIndex + 1].focus();
                    }
                }
            }
        }
    });

    // 检查是否已登录
    const authToken = sessionStorage.getItem('auth_token');
    if (authToken) {
        fetch(`${API_BASE_URL}/verify-token/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.valid) {
                    window.location.href = '/main/';
                } else {
                    sessionStorage.removeItem('auth_token');
                    sessionStorage.removeItem('user_info');
                }
            })
            .catch(error => {
                console.log('Token验证失败:', error);
            });
    }

    // 表单自动保存（可选功能）
    const autoSaveFields = ['firstName', 'lastName', 'username', 'email', 'phone'];
    autoSaveFields.forEach(fieldName => {
        const input = document.getElementById(fieldName);
        if (input) {
            input.addEventListener('input', function () {
                localStorage.setItem(`register_${fieldName}`, this.value);
            });

            // 页面加载时恢复数据
            const savedValue = localStorage.getItem(`register_${fieldName}`);
            if (savedValue) {
                input.value = savedValue;
            }
        }
    });

    // 页面卸载时清理自动保存的数据
    window.addEventListener('beforeunload', function () {
        autoSaveFields.forEach(fieldName => {
            localStorage.removeItem(`register_${fieldName}`);
        });
    });
});
